package com.jjw.route.algorithm;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
 
public class RandomUserNameAlgorithm {
    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789";
    private static final int NAME_LENGTH = 8;
    private static final int MAX_ATTEMPTS = 1000;
    private static Set<String> existingNames = new HashSet<>();
 
    public static String generateUserName() {
        Random random = new Random();
        String userName;
        int attempts = 0;
 
        do {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < NAME_LENGTH; i++) {
                int index = random.nextInt(CHARACTERS.length());
                sb.append(CHARACTERS.charAt(index));
            }
            userName = sb.toString();
            attempts++;
        } while (existingNames.contains(userName) & attempts < MAX_ATTEMPTS);
 
        if (attempts == MAX_ATTEMPTS) {
            throw new RuntimeException("Failed to generate a unique username after " + attempts + " attempts.");
        }
 
        existingNames.add(userName);
        return userName;
    }
}